package com.hulushuju.core.net.http.okhttp;

import com.hulushuju.core.net.http.HttpRequest;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: Hanjiafeng
 * @Date: 2019-05-29
 * @Desc:
 */
public class OkHttpRequestImpl extends HttpRequest {
    @Override
    @SuppressWarnings("unchecked")
    public <T> T convertRequest(Class<T> c) {
        Request request = null;
        try {
            Request.Builder builder = new Request.Builder();

            //初始化OkHttp的Headers
            Headers.Builder headersBuilder = new Headers.Builder();
            Map<String, List<String>> headersMap = getHeaders();
            Set<String> keySet = headersMap.keySet();
            for (String key : keySet) {
                List<String> values = headersMap.get(key);
                for (String value : values) {
                    headersBuilder.add(key, value);
                }
            }
            Headers headers = headersBuilder.build();

            //初始化Method
            String method = getMethod().getMethod();
            //初始化RequestBody
            RequestBody requestBody = null;
            if (!method.equalsIgnoreCase(Method.GET.getMethod())) {
                MediaType mediaType = MediaType.parse(getContentType().getType());
                requestBody = RequestBody.create(mediaType, getFormData());
            }

            //build
            request = builder.url(getUrl())
                    .headers(headers)
                    .method(method, requestBody).build();


            request = builder.build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) request;
    }
}
